package com.penghaisoft.microwms.product.web.controller.intowarehouse;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IWmsCommonService;
import com.penghaisoft.microwms.common.util.ExcelExpUtil;
import com.penghaisoft.microwms.common.wms.model.ProHandIn;
import com.penghaisoft.microwms.common.wms.model.ProHandInSn;
import com.penghaisoft.microwms.common.wms.model.ProOrderInSn;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.service.IBaseDictionaryService;
import com.penghaisoft.microwms.product.service.IProHandInService;
import com.penghaisoft.microwms.product.service.IProHandInSnService;
import com.penghaisoft.microwms.product.service.IProOrderInSnService;
import com.penghaisoft.microwms.product.service.IProStorageSnService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description 成品入库管理相关Controller
 * @author luoteng
 * @date 2018年6月6日 下午3:01:43
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/intowarehouse")
@Slf4j
public class IntoWarehouseController extends BaseController {

	@Autowired
	private IProOrderInSnService proOrderInSnService;

	@Autowired
	private IProHandInService proHandInService;
	
	@Autowired
	private IProHandInSnService proHandInSnService;

	@Autowired
	private IWmsCommonService wmsCommonService;

	@Autowired
	private IProStorageSnService proStorageSnService;

	@Autowired
	private IBaseDictionaryService baseDictionaryService;

	/**
	 * 新增记录
	 * 
	 * @param proOrderInSn
	 * @return
	 */
	@PostMapping("proorderin/c")
	public TransResult create(ProOrderInSn proOrderInSn) {
		proOrderInSn.preInsert();
		Resp resp = proOrderInSnService.create(proOrderInSn);
		return fromResp(resp);
	}

	/**
	 * 删除记录（逻辑删除active_flag=0)
	 * 
	 * @param proOrderInSn
	 * @return
	 */
	@PostMapping("proorderin/d")
	public TransResult delete(ProOrderInSn proOrderInSn) {
		proOrderInSn.preUpdate();
		Resp resp = proOrderInSnService.delete(proOrderInSn);
		return fromResp(resp);
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @return
	 */
	@PostMapping("proorderin/list")
	public TransResult list(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProOrderInSn proOrderInSn) {
		// 入库状态 0：创建 1：已下线入库
		// proOrderInSn.setBarcodeStatus("1");
		Pager<ProOrderInSn> result = proOrderInSnService.findListByCondition(
				page, rows, proOrderInSn);

		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}

		return success(result);
	}

	/**
	 * @Title: listSnExp
	 * @Description: 下线入库明细导出
	 * @author jzh
	 * @throws
	 */
	@GetMapping("proorderin/listExp")
	public String listSnExp(ProOrderInSn proOrderInSn,
			HttpServletRequest request, HttpServletResponse response) {

		List<ProOrderInSn> dataList = proOrderInSnService
				.findListExp(proOrderInSn);

		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type_p");
		List<BaseDictionary> list1 = baseDictionaryService
				.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (ProOrderInSn tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断型号类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
						// 判断状态
						if ("0".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("未入库");
						} else if ("1".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("已入库");
						}
					}
				}
			}
		}

		List<Map> columnList = new ArrayList<Map>();
		Map<String, String> columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "条码");
		columnMap.put("columnBeanName", "barcode");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "数量");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "状态");
		columnMap.put("columnBeanName", "barcodeStatus");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "下线时间");
		columnMap.put("columnBeanName", "gmtCreate");
		columnList.add(columnMap);
		columnMap = new HashMap<String, String>();
		columnMap.put("columnComment", "入库时间");
		columnMap.put("columnBeanName", "proInDate");
		columnList.add(columnMap);

		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);

		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "成品下线入库明细" + sdfDate + ".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "sucess";
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @return
	 */
	@PostMapping("proorderin/model/list/old")
	// @PostMapping("proorderin/model/list")
	public TransResult listSelect(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProOrderInSn proOrderInSn) {
		// 入库状态 0：创建 1：已下线入库
		// proOrderInSn.setBarcodeStatus("1");
		Pager<ProOrderInSn> result = proOrderInSnService.findModelList(page,
				rows, proOrderInSn);
		return success(result);
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @return
	 */
	@PostMapping("proorderin/model/list")
	public TransResult listSelectNew(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProStorageSn proStorageSn) {
		// 入库状态 0：创建 1：已下线入库
		// proOrderInSn.setBarcodeStatus("1");
		Pager<ProStorageSn> result = proOrderInSnService.findModelListNew(page,
				rows, proStorageSn);
		return success(result);
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("proorderin/r/{id}")
	public TransResult queryById(@PathVariable String id) {
		ProOrderInSn proOrderInSn = proOrderInSnService.findById(id);
		return success(proOrderInSn);
	}

	/**
	 * 修改记录
	 * 
	 * @param proOrderInSn
	 * @return
	 */
	@PostMapping("proorderin/u")
	public TransResult update(ProOrderInSn proOrderInSn) {
		proOrderInSn.preUpdate();
		Resp resp = proOrderInSnService.update(proOrderInSn);
		return fromResp(resp);
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @return
	 */
	@PostMapping("prohandin/list")
	public TransResult handInlist(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProHandIn proHandIn) {
		proHandIn.setActiveFlag("1");
		Pager<ProHandIn> result = proHandInService.findListByCondition(page,
				rows, proHandIn);
		return success(result);
	}
	
	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @return
	 */
	@PostMapping("prohandinsn/list")
	public TransResult handInlist(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProHandInSn proHandInSn) {
		proHandInSn.setActiveFlag("1");
		Pager<ProHandInSn> result = proHandInSnService.findListByCondition(page,
				rows, proHandInSn);
		return success(result);
	}

	/**
	 * @Title proHandInCreate
	 * @Description 成品手工入库批量新增
	 * @author luoteng
	 * @date 2018年6月13日:下午3:27:54
	 * @param proHandIn
	 * @return TransResult
	 */
	@PostMapping("prohandin/batch/insert")
	public TransResult proHandInCreate(@RequestBody List<ProHandIn> list) {
		TransResult transResult = new TransResult();
		if (list == null || list.isEmpty()) {
			transResult.setCode(Constant.FAIL);
			transResult.setMsg("请选择成品型号及数量！");
			return transResult;
		} else {
			String handInNo = wmsCommonService.getProShortSeq5(
					Constant.SEQ_PREFIX_SHORT_SGR,
					Constant.SEQ_PREFIX_SHORT_REDIS_PRO_SGR, 1).get(0);
			Resp resp = proHandInService.batchInsert(list, handInNo,
					getLoginName());

			transResult.setCode(resp.getCode());
			transResult.setMsg(resp.getMsg());
		}

		return transResult;
	}

	/**
	 * @Title proHandInUpdate
	 * @Description 手工入库单 单条修改
	 * @author luoteng
	 * @date 2018年6月29日:下午12:59:06
	 * @param proHandIn
	 * @return TransResult
	 */
	@PostMapping("prohandin/update")
	public TransResult proHandInUpdate(ProHandIn proHandIn) {
		TransResult transResult = new TransResult();
		transResult.setCode(Constant.SUCCESS);
		ProHandIn ob = new ProHandIn();
		ob.setActiveFlag("1");
		ob.setHandInId(proHandIn.getHandInId());

		List<ProHandIn> list = proHandInService.queryListByAny(ob);
		if (list != null && !list.isEmpty()) {
			ProHandIn tmp = list.get(0);
			
			BigDecimal realAmount = tmp.getRealAmount() == null ? BigDecimal.ZERO : tmp.getRealAmount();
			BigDecimal modiAmount = proHandIn.getRequireAmount() == null ? BigDecimal.ZERO : proHandIn.getRequireAmount();
			
			// 0新建 1入库中 2入库完成
			if (tmp.getHandInStatus() != null && tmp.getHandInStatus().equals("2")) {
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("状态为入库完成的手工入库单不能修改！");
				return transResult;
			}else if(realAmount.compareTo(modiAmount) > 0){
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("手工入库单中该型号的需求数量不能修改小于当前实际数量！");
				return transResult;
			}
			
			if(!tmp.getModel().equals(proHandIn.getModel())){
				if(realAmount.compareTo(BigDecimal.ZERO) > 0){
					transResult.setCode(Constant.FAIL);
					transResult.setMsg("入库中的手工入库单不能修改入库型号！若想修改型号，请先退扫已扫码记录！");
					return transResult;
				}
			}
		}

		proHandIn.setLastModifiedBy(getLoginName());
		proHandIn.setGmtModified(new Date());
		proHandInService.updateNew(proHandIn);

		return transResult;
	}

	/**
	 * @Title getProHandInList
	 * @Description 根据手工入库单号查询列表
	 * @author luoteng
	 * @date 2018年6月13日:下午4:52:17
	 * @param contractNo
	 * @return TransResult
	 */
	@GetMapping("prohandin/get/{handInNo}")
	public TransResult getProHandInList(
			@PathVariable("handInNo") String handInNo) {
		TransResult transResult = new TransResult();
		transResult.setCode(Constant.SUCCESS);

		ProHandIn ob = new ProHandIn();
		ob.setActiveFlag("1");
		ob.setHandInNo(handInNo);

		List<ProHandIn> list = new ArrayList<ProHandIn>();
		list = proHandInService.queryListByAny(ob);
		if (list != null && !list.isEmpty()) {
			for (ProHandIn tmp : list) {
				// 0新建 1入库中 2入库完成
				if (tmp.getHandInStatus() != null && tmp.getHandInStatus().equals("2")) {
					transResult.setCode(Constant.FAIL);
					transResult.setMsg("状态为入库完成的手工入库单不能修改！");
					return transResult;
				}
			}
			transResult.setData(list);
		}

		return transResult;
	}

	/**
	 * @Title getProHandInList
	 * @Description 根据手工入库单号查询列表
	 * @author luoteng
	 * @date 2018年6月13日:下午4:52:17
	 * @param contractNo
	 * @return TransResult
	 */
	@GetMapping("prohandin/get/id/{handInId}")
	public TransResult getProHandInIdList(
			@PathVariable("handInId") String handInId) {
		TransResult transResult = new TransResult();
		transResult.setCode(Constant.SUCCESS);

		ProHandIn ob = new ProHandIn();
		ob.setActiveFlag("1");
		ob.setHandInId(Integer.parseInt(handInId));

		List<ProHandIn> list = proHandInService.queryListByAny(ob);
		if (list != null && !list.isEmpty()) {
			ProHandIn tmp = list.get(0);
			// 0新建 1入库中 2入库完成
			if (tmp.getHandInStatus() != null && tmp.getHandInStatus().equals("2")) {
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("状态为入库完成的手工入库单不能修改！");
				return transResult;
			}
			transResult.setData(tmp);
		}

		return transResult;
	}

	@PostMapping("charge/list/in")
	public TransResult chargeListIn(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		Pager<ProStorageSn> result = proStorageSnService
				.findProStorageSnCharge(page, rows, proStorageSn);

		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}

		return success(result);
	}

}
